package com.xusiyan08.controller;

import com.xusiyan08.dto.MessageDto;
import com.xusiyan08.entity.Message;
import com.xusiyan08.entity.User;
import com.xusiyan08.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/messages")
@CrossOrigin(origins = "*")
public class MessageController {

    @Autowired
    private MessageService messageService;
    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @GetMapping("/conversations/{userId}")
    public ResponseEntity<List<User>> getConversationsUsers(@PathVariable Long userId) {
        List<User> conversationUsers = messageService.getConversationsUsers(userId);
        return ResponseEntity.ok(conversationUsers);
    }


    @PostMapping
    public ResponseEntity<?> sendMessage(@RequestBody Message message) {
        Message savedMessage = messageService.sendMessage(message);
        logger.info("Received message in backend: senderId={}, receiverId={}, content={}",
                message.getSenderId(), message.getReceiverId(), message.getContent());
        Logger logger = LoggerFactory.getLogger(MessageController.class);
        return ResponseEntity.ok(savedMessage);
    }

    @GetMapping("/received/{userId}")
    public ResponseEntity<List<Message>> getReceivedMessages(@PathVariable Long userId) {
        List<Message> messages = messageService.getReceivedMessages(userId);
        return ResponseEntity.ok(messages);
    }

    @GetMapping("/conversation/{userId1}/{userId2}")
    public ResponseEntity<List<Message>> getConversation(@PathVariable Long userId1, @PathVariable Long userId2) {
        List<Message> messages = messageService.getConversation(userId1, userId2);
        return ResponseEntity.ok(messages);
    }

    @PutMapping("/{messageId}/read")
    public ResponseEntity<?> markAsRead(@PathVariable Long messageId) {
        Message message = messageService.markAsRead(messageId);
        return ResponseEntity.ok(message);
    }

    @PostMapping("/comment")
    public ResponseEntity<Message> addComment(@RequestBody Message comment) {
        logger.info("Received comment in controller: senderId={}, receiverId={}, itemId={}, content={}",
                comment.getSenderId(), comment.getReceiverId(), comment.getItemId(), comment.getContent());
        Message savedComment = messageService.addComment(comment);
        return ResponseEntity.ok(savedComment);
    }

    @GetMapping("/item/{itemId}/comments")
    public ResponseEntity<List<MessageDto>> getCommentsByItemId(@PathVariable Long itemId) {
        List<MessageDto> comments = messageService.getCommentsByItemId(itemId);
        return ResponseEntity.ok(comments);
    }

    @GetMapping("/unread-comments/seller/{sellerId}")
    public ResponseEntity<Boolean> hasUnreadCommentsForSeller(@PathVariable Long sellerId) {
        boolean hasUnread = messageService.hasUnreadCommentsForSeller(sellerId);
        return ResponseEntity.ok(hasUnread);
    }

    @GetMapping("/unread-comments/item/{itemId}/{receiverId}")
    public ResponseEntity<Boolean> hasUnreadCommentsForItem(@PathVariable Long itemId, @PathVariable Long receiverId) {
        boolean hasUnread = messageService.hasUnreadCommentsForItem(itemId, receiverId);
        return ResponseEntity.ok(hasUnread);
    }

    @DeleteMapping("/comment/{messageId}/{userId}")
    public ResponseEntity<String> deleteComment(@PathVariable Long messageId, @PathVariable Long userId) {
        try {
            messageService.deleteComment(messageId, userId);
            return ResponseEntity.ok("评论删除成功");
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getMessage());
        }
    }
}